package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.bean.AttendanceClassData;
import com.lzx.iteam.bean.AttendanceData;
import com.lzx.iteam.bean.ScheduleManager;
import com.lzx.iteam.net.*;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.selectdate.WheelView;
import com.lzx.iteam.widget.selectdate.adapter.NumericWheelAdapter;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import static com.lzx.iteam.DialerApp.mContext;

/**
 * Created by Megan on 16/4/8.
 */
public class AttendanceSettingActivity extends Activity implements View.OnClickListener {


    private LinearLayout mLlBack;
    private TextView mOk,mTvSave;
    private EditText mEtName;
    private TextView mTvStartTime1, mTvEndTime1, mTvStartTime2, mTvEndTime2, mTvWorkDate, mTvMember, mTvAddress, mTvDeviation, mTvWifi, mTvWifiNote;
    private TextView mTvStartTimeText1, mTvEndTimeText1, mTvStartTimeText2, mTvEndTimeText2;
    private TextView mTvTypeOne, mTvTypeTwo;
    private ToggleButton mTbIfWifi;
    private View mWifiLine, mTypeLine;
    private RelativeLayout mRlStartTime1, mRlEndTime1, mRlStartTime2, mRlEndTime2, mRlWorkDate, mRlMember, mRlAddress, mRlDeviation, mRlIfWifi, mRlWifi;
    private ImageView mIvFixed,mIvSub;
    private LinearLayout mLayoutSub,mLayoutSubClass;
    private View mLayoutFixed;

    private WheelView hour;
    private WheelView mins;
    private int mStartHour1 = 9, mEndHour1 = 12, mStartHour2 = 13, mEndHour2 = 18;
    private int mStartMinute1 = 0, mEndMinute1 = 0, mStartMinute2 = 30, mEndMinute2 = 0;
    private String mStartTime1 = "9:00", mEndTime1 = "12:00";
    private String mStartTime2 = "13:30", mEndTime2 = "18:00";

    private String mWorkDate = "1,2,3,4,5", mMember, mAddress, mDeviation = "300", mMemberCount, mName;
    private String mWifiMsg;
    private int mIsQuartic;//0：一天一次上下班打卡，1：一天两次上下班打卡
    private String mGroupName;
    private String mUserType;
    private String mContactId;
    private boolean flag;   // true:创建考勤   false：设置考勤
    private int mAttendanceType; // 默认 0: 固定考勤  1: 排班
    private PreferenceUtil mPreferenceUtil;
    private AttendanceData attendanceData;
    private PopupWindow mTimePop;
    private Calendar c;
    private ArrayList<AttendanceClassData> mSubClass = new ArrayList<>();

    private final int REQUEST_CODE_WORKDATE = 100;
    private final int REQUEST_CODE_ADDRESS = 101;
    private final int REQUEST_CODE_DEVIATION = 102;
    private final int REQUEST_CODE_MEMBER = 103;
    private final int REQUEST_CODE_WIFI = 104;
    private final int REQUEST_CODE_SUBCLASS = 105;

    private final int ADD_NEW_ATTENDANCE = 1000;
    private final int UPDATE_ATTENDANCE = 1001;
    private final int GET_ATTENDANCE_MEMBER = 1002;
    private final int REMOVE_ATTENDANCE_MEMBER = 1003;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ADD_NEW_ATTENDANCE:
                    if (msg.arg1 == 0) {
                        AttendanceData data = (AttendanceData) msg.obj;
                        attendanceData.set_id(data.get_id());
                        if (mAttendanceType == 0){
                            Intent intent = new Intent(AttendanceSettingActivity.this, AttendanceCreateActivity.class);
                            intent.putExtra("group_id", attendanceData.getGroupId());
                            intent.putExtra("group_name", mGroupName);
                            intent.putExtra("user_type", mUserType);
                            intent.putExtra("contact_id", mContactId);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                        }else{  // 设置排班
                            Intent intent = new Intent(AttendanceSettingActivity.this, AttendanceSubClassExcleActivity.class);
                            intent.putExtra("group_id", attendanceData.getGroupId());
                            intent.putExtra("form_id", attendanceData.get_id());
                            intent.putExtra("group_name", mGroupName);
                            intent.putExtra("user_type", mUserType);
                            intent.putExtra("contact_id", mContactId);
                            intent.putExtra("sub_class",data.getSubForms());
                            startActivity(intent);
                        }
                        finish();
                    } else if (msg.arg1 == 5001) {
                        HashMap<String, String> map = (HashMap<String, String>) msg.obj;
                        String backMsg = map.get("msg");
                        String backData = map.get("data");
                        showNoticeDlg(backMsg, backData);

                    } else {
                        Toast.makeText(AttendanceSettingActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        /*if (msg.arg1 == 500) {
                            Intent intent = new Intent(AttendanceSettingActivity.this, AttendanceCreateActivity.class);
                            intent.putExtra("group_id", attendanceData.getGroupId());
                            intent.putExtra("group_name", mGroupName);
                            intent.putExtra("user_type", mUserType);
                            intent.putExtra("contact_id", mContactId);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finish();
                        }*/
                    }
                    break;
                case UPDATE_ATTENDANCE:
                    if (msg.arg1 == 0) {
                        AttendanceData data = (AttendanceData) msg.obj;
                        if (data.isNextDayTakeEffect()) {
                            mPreferenceUtil.save(data.get_id(), DateUtil.getYearDate(System.currentTimeMillis()));
                        }
                        Intent intent = new Intent(AttendanceSettingActivity.this, AttendanceCreateActivity.class);
                        intent.putExtra("group_id", attendanceData.getGroupId());
                        intent.putExtra("group_name", mGroupName);
                        intent.putExtra("user_type", mUserType);
                        intent.putExtra("contact_id", mContactId);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        /*if (mAttendanceType == 0){
                        }else{
                            Intent intent = new Intent(AttendanceSettingActivity.this, AttendanceSubClassExcleActivity.class);
                            intent.putExtra("group_id", attendanceData.getGroupId());
                            intent.putExtra("form_id", attendanceData.get_id());
                            intent.putExtra("group_name", mGroupName);
                            intent.putExtra("user_type", mUserType);
                            intent.putExtra("contact_id", mContactId);
                            intent.putExtra("sub_class_data",mSubClass);
                            startActivity(intent);
                        }*/
                        finish();
                    } else if (msg.arg1 == 5001) {
                        HashMap<String, String> map = (HashMap<String, String>) msg.obj;
                        String backMsg = map.get("msg");
                        String backData = map.get("data");
                        showNoticeDlg(backMsg, backData);

                    } else {
                        Toast.makeText(AttendanceSettingActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case REMOVE_ATTENDANCE_MEMBER:
                    if (msg.arg1 == 0) {
                        int backResult = (Integer) msg.obj;
                        if (backResult == 1) {
                            if (flag) {
                                addAttendanceMsg();
                            } else {
                                updateAttendanceMsg();
                            }
                            /*Intent intent = new Intent(AttendanceSettingActivity.this, AttendanceCreateActivity.class);
                            intent.putExtra("group_id", attendanceData.getGroupId());
                            intent.putExtra("group_name", mGroupName);
                            intent.putExtra("user_type", mUserType);
                            intent.putExtra("contact_id", mContactId);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finish();*/
                        } else {
                            Toast.makeText(AttendanceSettingActivity.this, "删除失败,请重新操作", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(AttendanceSettingActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case GET_ATTENDANCE_MEMBER:
                    if (msg.arg1 == 0) {
                        ArrayList<ScheduleManager> managers = (ArrayList<ScheduleManager>) msg.obj;
                        JSONArray jsonArray = new JSONArray();
                        for (ScheduleManager manager : managers) {
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("contact_name", manager.getUserName());
                                jsonObject.put("user_id", manager.getUserId());
                                jsonObject.put("user_image", manager.getAvatar());
                                jsonObject.put("_id", manager.getContact_id());
                                jsonObject.put("contact_id", manager.getContactId());
                                jsonObject.put("deviation", manager.getDeviation());
                                jsonArray.put(jsonObject);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                        mMember = jsonArray.toString();
                        mMemberCount = jsonArray.length() + "";
                        attendanceData.setMembers(mMember);
                        attendanceData.setMemberCount(mMemberCount);
                    } else {
                        Toast.makeText(AttendanceSettingActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();

                    }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.attendance_setting_layout);
        initViews();
        getIntentData();
    }

    private void initViews() {
        mLlBack = (LinearLayout) findViewById(R.id.ll_attendance_setting_back);
        mOk = (TextView) findViewById(R.id.tv_attendance_setting_ok);
        mTvSave = (TextView) findViewById(R.id.tv_attendance_setting_save);
        mEtName = (EditText) findViewById(R.id.et_attendance_setting_name);

        mTvStartTime1 = (TextView) findViewById(R.id.tv_attendance_setting_starttime1);
        mTvEndTime1 = (TextView) findViewById(R.id.tv_attendance_setting_endtime1);
        mTvStartTime2 = (TextView) findViewById(R.id.tv_attendance_setting_starttime2);
        mTvEndTime2 = (TextView) findViewById(R.id.tv_attendance_setting_endtime2);

        mTvStartTimeText1 = (TextView) findViewById(R.id.tv_attendance_setting_starttime_text1);
        mTvEndTimeText1 = (TextView) findViewById(R.id.tv_attendance_setting_endtime_text1);
        mTvStartTimeText2 = (TextView) findViewById(R.id.tv_attendance_setting_starttime_text2);
        mTvEndTimeText2 = (TextView) findViewById(R.id.tv_attendance_setting_endtime_text2);

        mTvWorkDate = (TextView) findViewById(R.id.tv_attendance_setting_workdate);
        mTvMember = (TextView) findViewById(R.id.tv_attendance_setting_member);
        mTvAddress = (TextView) findViewById(R.id.tv_attendance_setting_address);
        mTvDeviation = (TextView) findViewById(R.id.tv_attendance_setting_deviation);
        mTvWifi = (TextView) findViewById(R.id.tv_attendance_setting_wifi);
        mTvTypeOne = (TextView) findViewById(R.id.tv_attendance_setting_type_one);
        mTvTypeTwo = (TextView) findViewById(R.id.tv_attendance_setting_type_two);
        mWifiLine = (View) findViewById(R.id.v_attendance_setting_wifi_line);
        mTypeLine = (View) findViewById(R.id.v_attendance_setting_type_line);

        mRlStartTime1 = (RelativeLayout) findViewById(R.id.rl_attendance_setting_starttime1);
        mRlEndTime1 = (RelativeLayout) findViewById(R.id.rl_attendance_setting_endtime1);
        mRlStartTime2 = (RelativeLayout) findViewById(R.id.rl_attendance_setting_starttime2);
        mRlEndTime2 = (RelativeLayout) findViewById(R.id.rl_attendance_setting_endtime2);
        mRlWorkDate = (RelativeLayout) findViewById(R.id.rl_attendance_setting_workdate);
        mRlMember = (RelativeLayout) findViewById(R.id.rl_attendance_setting_member);
        mRlAddress = (RelativeLayout) findViewById(R.id.rl_attendance_setting_address);
        mRlDeviation = (RelativeLayout) findViewById(R.id.rl_attendance_setting_deviation);
        mRlIfWifi = (RelativeLayout) findViewById(R.id.rl_attendance_setting_if_wifi);
        mRlWifi = (RelativeLayout) findViewById(R.id.rl_attendance_setting_wifi);
        mTbIfWifi = (ToggleButton) findViewById(R.id.tb_attendance_setting_if_wifi);
        mTvWifiNote = (TextView) findViewById(R.id.tv_attendance_setting_wifi_note_text);

        mIvFixed = (ImageView) findViewById(R.id.iv_attendance_setting_fixed);
        mLayoutFixed = findViewById(R.id.ll_attendance_setting_fixed);
        mIvSub = (ImageView) findViewById(R.id.iv_attendance_setting_sub);
        mLayoutSub = (LinearLayout) findViewById(R.id.ll_attendance_setting_sub);
        mLayoutSubClass = (LinearLayout) findViewById(R.id.ll_attendance_setting_times);

        mLayoutSub.setOnClickListener(this);
        mIvFixed.setOnClickListener(this);
        mIvSub.setOnClickListener(this);

        mLlBack.setOnClickListener(this);
        mOk.setOnClickListener(this);
        mTvSave.setOnClickListener(this);

        mRlStartTime1.setOnClickListener(this);
        mRlEndTime1.setOnClickListener(this);
        mRlStartTime2.setOnClickListener(this);
        mRlEndTime2.setOnClickListener(this);
        mRlWorkDate.setOnClickListener(this);
        mRlMember.setOnClickListener(this);
        mRlAddress.setOnClickListener(this);
        mRlDeviation.setOnClickListener(this);
        mRlIfWifi.setOnClickListener(this);
        mRlWifi.setOnClickListener(this);
        mTvTypeOne.setOnClickListener(this);
        mTvTypeTwo.setOnClickListener(this);
    }


    private void getIntentData() {
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        Intent intent = getIntent();
        mGroupName = intent.getStringExtra("group_name");
        mUserType = intent.getStringExtra("user_type");
        mContactId = intent.getStringExtra("contact_id");
        attendanceData = (AttendanceData) intent.getSerializableExtra("attendanceData");
        if (StringUtil.isEmpty(attendanceData.get_id())) {
            flag = true;
        }
        mAddress = attendanceData.getAddress();
        mMember = attendanceData.getMembers();
        mMemberCount = attendanceData.getMemberCount();
        mAttendanceType = attendanceData.getFormType();
        setNullSubClass();
        setAttendanceStatues();
        if (mAttendanceType == 0){
            mIsQuartic = attendanceData.getIsQuartic();
            updateTypeView(mIsQuartic);
            if (!StringUtil.isEmpty(attendanceData.getStartWorkTime())) {
                mStartTime1 = attendanceData.getStartWorkTime();
                mStartHour1 = Integer.parseInt(mStartTime1.split(":")[0]);
                mStartMinute1 = Integer.parseInt(mStartTime1.split(":")[1]);

            }
            if (!StringUtil.isEmpty(attendanceData.getEndWorkTime())) {
                mEndTime2 = attendanceData.getEndWorkTime();
                mEndHour2 = Integer.parseInt(mEndTime2.split(":")[0]);
                mEndMinute2 = Integer.parseInt(mEndTime2.split(":")[1]);
            }
            if (!StringUtil.isEmpty(attendanceData.getNoonEndTime())) {
                mEndTime1 = attendanceData.getNoonEndTime();
                mEndHour1 = Integer.parseInt(mEndTime1.split(":")[0]);
                mEndMinute1 = Integer.parseInt(mEndTime1.split(":")[1]);
            }
            if (!StringUtil.isEmpty(attendanceData.getNoonStartTime())) {
                mStartTime2 = attendanceData.getNoonStartTime();
                mStartHour2 = Integer.parseInt(mStartTime2.split(":")[0]);
                mStartMinute2 = Integer.parseInt(mStartTime2.split(":")[1]);
            }

        }else if (mAttendanceType == 1){
            String subForms = attendanceData.getSubForms();
            try {
                mSubClass.clear();
                if (!StringUtil.isEmpty(subForms)){
                    JSONArray jsonArray = new JSONArray(subForms);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject sub = jsonArray.getJSONObject(i);
                        AttendanceClassData data = new AttendanceClassData();
                        data.setSub_name(sub.getString("sub_name"));
                        data.set_id(sub.getString("_id"));
                        data.setIs_quartic(sub.getInt("is_quartic"));
                        data.setStart_work_time(sub.getString("start_work_time"));
                        data.setEnd_work_time(sub.getString("end_work_time"));
                        if (sub.getInt("is_quartic") == 1){
                            data.setNoon_end_time(sub.getString("noon_end_time"));
                            data.setNoon_start_time(sub.getString("noon_start_time"));
                        }
                        mSubClass.add(data);
                    }
                }
                setSubClassData();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        mName = attendanceData.getName();
        if (!StringUtil.isEmpty(attendanceData.getWorkDate())) {
            mWorkDate = attendanceData.getWorkDate();
        }
        if (!StringUtil.isEmpty(attendanceData.getDeviation())) {
            mDeviation = attendanceData.getDeviation();
        }
        if (!StringUtil.isEmpty(mMember)) {
            try {
                JSONArray jsonArray = new JSONArray(mMember);
                mMemberCount = jsonArray.length() + "";
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            getAttendanceMemberList();
        }

        mTvMember.setText(mMemberCount + "人");
        mTvAddress.setText(mAddress);
        mTvStartTime1.setText(mStartTime1);
        mTvEndTime2.setText(mEndTime1);
        mTvStartTime2.setText(mStartTime2);
        mTvEndTime2.setText(mEndTime2);
        mTvDeviation.setText(mDeviation + "米");
        mEtName.setText(mName);
        if ((!StringUtil.isEmpty(mName)) && (mName.length() > 0)) {
            mEtName.setSelection(mName.length());
        }
        setWorkDate();
        try {
            if (StringUtil.isEmpty(attendanceData.get_id())) {
                if (attendanceData.getWifiMsg() == null || new JSONArray(attendanceData.getWifiMsg()).length() == 0) {
                    JSONArray jsonArray = new JSONArray();
                    WifiInfo wifiInfo = NetworkUtil.getWifiInfo(this);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("wifi_mac", wifiInfo.getBSSID());
                    jsonObject.put("wifi_name", wifiInfo.getSSID());
                    jsonArray.put(jsonObject);
                    attendanceData.setWifiMsg(jsonArray.toString());
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            mWifiMsg = attendanceData.getWifiMsg();
            StringBuilder sb = new StringBuilder();
            if (mWifiMsg != null) {
                JSONArray jsonArray = new JSONArray(mWifiMsg);
                if (jsonArray.length() > 0) {
                    mRlWifi.setVisibility(View.VISIBLE);
                    mTvWifiNote.setVisibility(View.VISIBLE);
                    mWifiLine.setVisibility(View.VISIBLE);
                    setIfWifi("1");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        sb.append(jsonObject.getString("wifi_name")).append(",");
                    }
                    mTvWifi.setText(sb.substring(0, sb.length() - 1));
                } else {
                    setIfWifi("0");
                    mRlWifi.setVisibility(View.GONE);
                    mTvWifiNote.setVisibility(View.GONE);
                    mWifiLine.setVisibility(View.GONE);
                }
            } else {
                setIfWifi("0");
                mRlWifi.setVisibility(View.GONE);
                mTvWifiNote.setVisibility(View.GONE);
                mWifiLine.setVisibility(View.GONE);
            }

        } catch (JSONException e) {
            e.printStackTrace();
            setIfWifi("0");
            mRlWifi.setVisibility(View.GONE);
            mTvWifiNote.setVisibility(View.GONE);
            mWifiLine.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_attendance_setting_back:
                showCancelSetDlg();
                break;
            case R.id.tv_attendance_setting_save:
            case R.id.tv_attendance_setting_ok:
                if (StringUtil.isEmpty(mStartTime1)) {
                    Toast.makeText(this, " 对不起，上班时间不能为空，请选择上班时间", Toast.LENGTH_LONG).show();
                    break;
                }
                if (StringUtil.isEmpty(mEndTime2)) {
                    Toast.makeText(this, " 对不起，下班时间不能为空，请选择下班时间", Toast.LENGTH_LONG).show();
                    break;
                }
                if (StringUtil.isEmpty(attendanceData.getAddress())) {
                    Toast.makeText(this, " 对不起，地址不能为空，请选择地址", Toast.LENGTH_LONG).show();
                    break;
                }
                mName = mEtName.getText().toString();
                if (StringUtil.isEmpty(mName)) {
                    Toast.makeText(this, " 对不起，考勤名字不能为空，请输入名字", Toast.LENGTH_LONG).show();
                    break;
                }

                attendanceData.setMemberCount(mMemberCount);
                attendanceData.setMembers(mMember);
                attendanceData.setName(mName);
                attendanceData.setStartWorkTime(mStartTime1);
                attendanceData.setEndWorkTime(mEndTime2);
                attendanceData.setDeviation(mDeviation);
                attendanceData.setWorkDate(mWorkDate);
                if (mIsQuartic == 1) {
                    attendanceData.setNoonEndTime(mEndTime1);
                    attendanceData.setNoonStartTime(mStartTime2);
                }
                if (getIfWifi() == 0) {
                    mWifiMsg = "";
                }
                attendanceData.setWifiMsg(mWifiMsg);
                if (StringUtil.isEmpty(attendanceData.get_id())) {
                    addAttendanceMsg();
                } else {
                    updateAttendanceMsg();
                }
                break;
            case R.id.rl_attendance_setting_starttime1:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AttendanceSettingActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showTimeSelectPop(1);
                break;
            case R.id.rl_attendance_setting_endtime1:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AttendanceSettingActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showTimeSelectPop(2);
                break;
            case R.id.rl_attendance_setting_starttime2:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AttendanceSettingActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showTimeSelectPop(3);
                break;
            case R.id.rl_attendance_setting_endtime2:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AttendanceSettingActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showTimeSelectPop(4);
                break;
            case R.id.rl_attendance_setting_workdate:
                Intent workdate = new Intent(AttendanceSettingActivity.this, AttendanceSelectWeekActivity.class);
                workdate.putExtra("workdate", mWorkDate);
                startActivityForResult(workdate, REQUEST_CODE_WORKDATE);
                break;
            case R.id.rl_attendance_setting_member:
                attendanceData.setName(mEtName.getText().toString());
                attendanceData.setStartWorkTime(mStartTime1);
                attendanceData.setEndWorkTime(mEndTime2);
                attendanceData.setDeviation(mDeviation);
                attendanceData.setWorkDate(mWorkDate);
                attendanceData.setIsQuartic(mIsQuartic);
                if (mIsQuartic == 1) {
                    attendanceData.setNoonEndTime(mEndTime1);
                    attendanceData.setNoonStartTime(mStartTime2);
                }
                if (getIfWifi() == 0) {
                    mWifiMsg = "";
                }
                attendanceData.setWifiMsg(mWifiMsg);

                Intent member = new Intent(AttendanceSettingActivity.this, AttendanceMemberActivity.class);
                member.setAction("attendance_member_add");
                member.putExtra("attendanceData", attendanceData);
                member.putExtra("group_id", attendanceData.getGroupId());
                member.putExtra("tag_id", "0");
                member.putExtra("tag_name", mGroupName);
                member.putExtra("group_name", mGroupName);
                member.putExtra("user_type", mUserType);
                member.putExtra("contact_id", mContactId);
                member.putExtra("where", "cloud");
                startActivityForResult(member, REQUEST_CODE_MEMBER);
                break;
            case R.id.rl_attendance_setting_address:
                Intent map = new Intent(AttendanceSettingActivity.this, BaiduMapActivity.class);
                map.setAction("attendance_update");
                map.putExtra("attendanceData", attendanceData);
                startActivityForResult(map, REQUEST_CODE_ADDRESS);
                break;
            case R.id.rl_attendance_setting_deviation:
                Intent deviation = new Intent(AttendanceSettingActivity.this, AttendanceDeviationActivity.class);
                deviation.putExtra("deviation", mDeviation);
                startActivityForResult(deviation, REQUEST_CODE_DEVIATION);
                break;
            case R.id.rl_attendance_setting_wifi:
                Intent wifi = new Intent(AttendanceSettingActivity.this, AttendanceWifiSettingActivity.class);
                wifi.putExtra("wifiMsg", mWifiMsg);
                wifi.putExtra("deviation", mDeviation);
                startActivityForResult(wifi, REQUEST_CODE_WIFI);
                break;
            case R.id.rl_attendance_setting_if_wifi:
                mTbIfWifi.toggle();
                if (mTbIfWifi.isChecked()) {
                    wifi = new Intent(AttendanceSettingActivity.this, AttendanceWifiSettingActivity.class);
                    wifi.putExtra("wifiMsg", mWifiMsg);
                    wifi.putExtra("deviation", mDeviation);
                    startActivityForResult(wifi, REQUEST_CODE_WIFI);
                }
                getIfWifi();
                break;
            case R.id.tv_attendance_setting_type_one:
                mIsQuartic = 0;
                updateTypeView(mIsQuartic);
                break;
            case R.id.tv_attendance_setting_type_two:
                mIsQuartic = 1;
                updateTypeView(mIsQuartic);
                break;
            case R.id.ll_attendance_setting_sub:
                Intent sub = new Intent(this,AttendanceSubClassActivity.class);
                if (mSubClass != null  && mSubClass.size() > 0){
                    sub.putExtra("sub_class",mSubClass);
                }
                if (attendanceData != null) {
                    sub.putExtra("group_id",attendanceData.getGroupId());
                    sub.putExtra("form_id",attendanceData.get_id());
                }
                startActivityForResult(sub,REQUEST_CODE_SUBCLASS);
                break;
            case R.id.iv_attendance_setting_fixed:
                if (mAttendanceType == 1){
                    mAttendanceType = 0;
                    setAttendanceStatues();
                }
                break;
            case R.id.iv_attendance_setting_sub:
                if (mAttendanceType == 0){
                    mAttendanceType = 1;
                    setAttendanceStatues();
                }
                break;
        }

    }

    /**
     * 设置考勤状态  固定班制 | 排班制
     */
    private void setAttendanceStatues(){
        if (mAttendanceType == 0){
            mLayoutFixed.setVisibility(View.VISIBLE);
            mLayoutSub.setVisibility(View.GONE);
            mIvFixed.setImageResource(R.drawable.iv_at_fixed_select);
            mIvSub.setImageResource(R.drawable.iv_at_schedule_normal);

            mTvSave.setText("保存");

        }else if (mAttendanceType == 1){
            mLayoutFixed.setVisibility(View.GONE);
            mLayoutSub.setVisibility(View.VISIBLE);
            mIvFixed.setImageResource(R.drawable.iv_at_fixed_normal);
            mIvSub.setImageResource(R.drawable.iv_at_schedule_select);

            if (flag){
                mTvSave.setText("保存\n并排班");
            }else{
                mTvSave.setText("保存");
            }
        }
    }

    /**
     * 设置班次数据
     */
    private void setSubClassData(){
        mLayoutSubClass.removeAllViews();
        for (int i = 0; i < mSubClass.size(); i++) {
            AttendanceClassData classData =  mSubClass.get(i);
            TextView sub = new TextView(mContext);
            String title = "";
            if (classData.getIs_quartic() == 0){
                title = classData.getSub_name() + "  " + classData.getStart_work_time() + "    " + checkTime(classData.getEnd_work_time());
            } else if (classData.getIs_quartic() == 1){
                title  = classData.getSub_name() + "  " + classData.getStart_work_time() + " - " + checkTime(classData.getNoon_end_time()) + "  " +checkTime(classData.getNoon_start_time()) + " - " +checkTime(classData.getEnd_work_time());
            }
            sub.setText(title);
            sub.setTextColor(Color.parseColor("#999999"));
            sub.setTextSize(13);
            // 父控件是LinearLayout 若是相对布局用RelativeLayout.LayoutParams
            LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
                  LinearLayout.LayoutParams.WRAP_CONTENT,
                  LinearLayout.LayoutParams.WRAP_CONTENT
            );
            // 需要 dp 转成像素单位
            linearParams.bottomMargin = Constants.dip2px(mContext,8);
            sub.setLayoutParams(linearParams);
            mLayoutSubClass.addView(sub);
        }
        if (mSubClass.size() == 0){
            setNullSubClass();
        }

    }

    /**
     * 设置 暂无 排班
     */
    private void setNullSubClass(){
        mLayoutSubClass.removeAllViews();
        TextView sub = new TextView(mContext);
        sub.setText("暂无设置班次");
        sub.setTextColor(Color.parseColor("#999999"));
        sub.setTextSize(13);
        // 父控件是LinearLayout 若是相对布局用RelativeLayout.LayoutParams
        LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
              LinearLayout.LayoutParams.WRAP_CONTENT,
              LinearLayout.LayoutParams.WRAP_CONTENT
        );
        // 需要 dp 转成像素单位
        linearParams.bottomMargin = Constants.dip2px(mContext,8);
        sub.setLayoutParams(linearParams);
        mLayoutSubClass.addView(sub);
    }

    private void setIfWifi(String flag) {
        if ("0".equals(flag)) {
            mTbIfWifi.setChecked(false);
        } else if ("1".equals(flag)) {
            mTbIfWifi.setChecked(true);
        }
    }

    private int getIfWifi() {
        if (mTbIfWifi.isChecked()) {
            mRlWifi.setVisibility(View.VISIBLE);
            mTvWifiNote.setVisibility(View.VISIBLE);
            mWifiLine.setVisibility(View.VISIBLE);
            try {
                String wifiMsg = attendanceData.getWifiMsg();
                StringBuilder sb = new StringBuilder();
                if (wifiMsg != null) {
                    JSONArray jsonArray = new JSONArray(wifiMsg);
                    if (jsonArray.length() > 0) {
                        setIfWifi("1");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            sb.append(jsonObject.getString("wifi_name")).append(",");
                        }
                        mTvWifi.setText(sb.substring(0, sb.length() - 1));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return 1;
        } else {
            mRlWifi.setVisibility(View.GONE);
            return 0;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ADDRESS:
                    attendanceData = (AttendanceData) data.getSerializableExtra("attendanceData");
                    mTvAddress.setText(attendanceData.getAddress());
                    break;
                case REQUEST_CODE_DEVIATION:
                    mDeviation = data.getStringExtra("deviation");
                    mTvDeviation.setText(mDeviation + "米");
                    break;
                case REQUEST_CODE_WORKDATE:
                    mWorkDate = data.getStringExtra("week");
                    setWorkDate();
                    break;
                case REQUEST_CODE_MEMBER:
                    mMember = data.getStringExtra("members");
                    mMemberCount = data.getStringExtra("memberCount");
                    attendanceData.setMemberCount(mMemberCount);
                    attendanceData.setMembers(mMember);
                    mTvMember.setText(mMemberCount + "人");
                    break;
                case REQUEST_CODE_WIFI:
                    mWifiMsg = data.getStringExtra("wifiMsg");
                    attendanceData.setWifiMsg(mWifiMsg);
                    int onlyWifi = data.getIntExtra("wifiOnly", 0);
                    if (onlyWifi == 1) {
                        attendanceData.setDeviation("0");
                        mDeviation = "0";
                        mTvDeviation.setText(mDeviation + "米");
                    } else {
                        if ("0".equals(mDeviation)) {
                            attendanceData.setDeviation("300");
                            mDeviation = "300";
                            mTvDeviation.setText(mDeviation + "米");
                        } else {
                            attendanceData.setDeviation(mDeviation);
                            mTvDeviation.setText(mDeviation + "米");
                        }
                    }
                    try {
                        StringBuilder sb = new StringBuilder();
                        JSONArray jsonArray = new JSONArray(mWifiMsg);
                        if (jsonArray.length() > 0) {
                            mRlWifi.setVisibility(View.VISIBLE);
                            mTvWifiNote.setVisibility(View.VISIBLE);
                            mWifiLine.setVisibility(View.VISIBLE);
                            setIfWifi("1");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                sb.append(jsonObject.getString("wifi_name")).append(",");
                            }
                            mTvWifi.setText(sb.substring(0, sb.length() - 1));
                        } else {
                            setIfWifi("0");
                            mTvWifi.setText("");
                            mRlWifi.setVisibility(View.GONE);
                            mTvWifiNote.setVisibility(View.GONE);
                            mWifiLine.setVisibility(View.GONE);

                            attendanceData.setDeviation("300");
                            mDeviation = "300";
                            mTvDeviation.setText(mDeviation + "米");

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case REQUEST_CODE_SUBCLASS:
                    mSubClass = (ArrayList<AttendanceClassData>) data.getSerializableExtra("sub_class");
                    if (mSubClass.size() > 0){
                        setSubClassData();
                    }else{
                        setNullSubClass();
                    }
                    break;
            }
        }
    }

    private String checkTime(String time){
        if (time.contains("-")){
            return time.replace("-","次日");
        }else{
            return time;
        }
    }


    /**
     * 选择时间
     *
     * @param type 1：上午上班时间 2：上午下班时间 3：下午上班时间 4：下午下班时间
     */
    public void showTimeSelectPop(final int type) {

        final View view = LayoutInflater.from(this).inflate(R.layout.select_time_pop_layout, null);

        hour = (WheelView) view.findViewById(R.id.new_hour);
        initHour();
        mins = (WheelView) view.findViewById(R.id.new_mins);
        initMins();
        // 设置当前时间
        if (type == 1) {
            hour.setCurrentItem(mStartHour1);
            mins.setCurrentItem(mStartMinute1);
        } else if (type == 2) {
            hour.setCurrentItem(mEndHour1);
            mins.setCurrentItem(mEndMinute1);
        } else if (type == 3) {
            hour.setCurrentItem(mStartHour2);
            mins.setCurrentItem(mStartMinute2);
        } else if (type == 4) {
            hour.setCurrentItem(mEndHour2);
            mins.setCurrentItem(mEndMinute2);
        }


        TextView bt = (TextView) view.findViewById(R.id.new_set);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == 1) {
                    if (mIsQuartic == 0) {
                        if (compareNextTime(hour.getCurrentItem(), mins.getCurrentItem(), mEndHour2, mEndMinute2)) {
                            mStartHour1 = hour.getCurrentItem();
                            mStartMinute1 = mins.getCurrentItem();
                            String time = "";
                            if (mStartMinute1 < 10) {
                                time = mStartHour1 + ":0" + mStartMinute1;
                            } else {
                                time = mStartHour1 + ":" + mStartMinute1;
                            }
                            mStartTime1 = time;
                            mTvStartTime1.setText(mStartTime1);
                        } else {
                            Toast.makeText(AttendanceSettingActivity.this, "当前时间不能大于下班时间", Toast.LENGTH_LONG).show();
                            return;
                        }
                    } else {
                        if (compareNextTime(hour.getCurrentItem(), mins.getCurrentItem(), mEndHour1, mEndMinute1)) {
                            mStartHour1 = hour.getCurrentItem();
                            mStartMinute1 = mins.getCurrentItem();
                            String time = "";
                            if (mStartMinute1 < 10) {
                                time = mStartHour1 + ":0" + mStartMinute1;
                            } else {
                                time = mStartHour1 + ":" + mStartMinute1;
                            }
                            mStartTime1 = time;
                            mTvStartTime1.setText(mStartTime1);
                        } else {
                            Toast.makeText(AttendanceSettingActivity.this, "当前时间不能大于上午下班时间", Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                } else if (type == 2) {
                    if (!compareNextTime(hour.getCurrentItem(), mins.getCurrentItem(), mStartHour2, mStartMinute2)) {
                        Toast.makeText(AttendanceSettingActivity.this, "当前时间不能大于下午上班时间", Toast.LENGTH_LONG).show();
                        return;
                    } else if (!compareLastTime(hour.getCurrentItem(), mins.getCurrentItem(), mStartHour1, mStartMinute1)) {
                        Toast.makeText(AttendanceSettingActivity.this, "当前时间不能小于上午上班时间", Toast.LENGTH_LONG).show();
                        return;
                    } else {
                        mEndHour1 = hour.getCurrentItem();
                        mEndMinute1 = mins.getCurrentItem();
                        String time = "";
                        if (mEndMinute1 < 10) {
                            time = mEndHour1 + ":0" + mEndMinute1;
                        } else {
                            time = mEndHour1 + ":" + mEndMinute1;
                        }
                        mEndTime1 = time;
                        mTvEndTime1.setText(mEndTime1);
                    }

                } else if (type == 3) {
                    if (!compareNextTime(hour.getCurrentItem(), mins.getCurrentItem(), mEndHour2, mEndMinute2)) {
                        Toast.makeText(AttendanceSettingActivity.this, "当前时间不能大于下午下班时间", Toast.LENGTH_LONG).show();
                        return;
                    } else if (!compareLastTime(hour.getCurrentItem(), mins.getCurrentItem(), mEndHour1, mEndMinute1)) {
                        Toast.makeText(AttendanceSettingActivity.this, "当前时间不能小于上午下班时间", Toast.LENGTH_LONG).show();
                        return;
                    } else {
                        mStartHour2 = hour.getCurrentItem();
                        mStartMinute2 = mins.getCurrentItem();
                        String time = "";
                        if (mStartMinute2 < 10) {
                            time = mStartHour2 + ":0" + mStartMinute2;
                        } else {
                            time = mStartHour2 + ":" + mStartMinute2;
                        }
                        mStartTime2 = time;
                        mTvStartTime2.setText(mStartTime2);
                    }
                } else if (type == 4) {
                    if (mIsQuartic == 0) {
                        if (compareLastTime(hour.getCurrentItem(), mins.getCurrentItem(), mStartHour1, mStartMinute1)) {
                            mEndHour2 = hour.getCurrentItem();
                            mEndMinute2 = mins.getCurrentItem();
                            String time = "";
                            if (mEndMinute2 < 10) {
                                time = mEndHour2 + ":0" + mEndMinute2;
                            } else {
                                time = mEndHour2 + ":" + mEndMinute2;
                            }
                            mEndTime2 = time;
                            mTvEndTime2.setText(mEndTime2);
                        } else {
                            Toast.makeText(AttendanceSettingActivity.this, "当前时间不能小于上班时间", Toast.LENGTH_LONG).show();
                            return;
                        }
                    } else {
                        if (compareLastTime(hour.getCurrentItem(), mins.getCurrentItem(), mStartHour2, mStartMinute2)) {
                            mEndHour2 = hour.getCurrentItem();
                            mEndMinute2 = mins.getCurrentItem();
                            String time = "";
                            if (mEndMinute2 < 10) {
                                time = mEndHour2 + ":0" + mEndMinute2;
                            } else {
                                time = mEndHour2 + ":" + mEndMinute2;
                            }
                            mEndTime2 = time;
                            mTvEndTime2.setText(mEndTime2);
                        } else {
                            Toast.makeText(AttendanceSettingActivity.this, "当前时间不能小于下午上班时间", Toast.LENGTH_LONG).show();
                            return;
                        }
                    }

                }

                mTimePop.dismiss();
            }
        });
        TextView cancel = (TextView) view.findViewById(R.id.new_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTimePop.dismiss();
            }
        });

        mTimePop = new PopupWindow(this);
        mTimePop.setBackgroundDrawable(new BitmapDrawable());
        mTimePop.setFocusable(true);
        mTimePop.setTouchable(true);
        mTimePop.setOutsideTouchable(true);
        mTimePop.setContentView(view);
        mTimePop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mTimePop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mTimePop.setAnimationStyle(R.style.bottomStyle);
        mTimePop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        mTimePop.update();
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mTimePop.dismiss();
                return false;
            }
        });
    }


    /**
     * 初始化时
     */
    private void initHour() {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 0, 23, "%02d");
        numericWheelAdapter.setLabel(" 时");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        hour.setViewAdapter(numericWheelAdapter);
        hour.setCyclic(true);
    }

    /**
     * 初始化分
     */
    private void initMins() {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 0, 59, "%02d", 1);
        numericWheelAdapter.setLabel(" 分");
//		numericWheelAdapter.setTextSize(15);  设置字体大小
        mins.setViewAdapter(numericWheelAdapter);
        mins.setCyclic(true);
    }

    /**
     * 取消设置
     */
    public void showCancelSetDlg() {
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(this);
        String okText = this.getString(R.string.label_btn_ok);
        String cancelText = this.getString(R.string.cancel);
        String notice = "是否确定放弃\n对考勤点的修改?";
        if (flag) {
            notice = "是否确定放弃\n新考勤点创建?";
        }
        mDialogUtil.titleDeleteMsgStyle(okText, cancelText, notice);
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                Intent intent = new Intent(AttendanceSettingActivity.this, AttendanceCreateActivity.class);
                intent.putExtra("group_id", attendanceData.getGroupId());
                intent.putExtra("group_name", mGroupName);
                intent.putExtra("user_type", mUserType);
                intent.putExtra("contact_id", mContactId);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }

    /**
     * 处理重复成员
     */
    public void showNoticeDlg(String msg, final String members) {
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(this);
        String okText = this.getString(R.string.label_btn_ok);
        String cancelText = this.getString(R.string.cancel);
        mDialogUtil.titleDeleteMsgStyle(okText, cancelText, msg);
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                removeMember(members);
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }


    /**
     * 创建考勤点
     */
    private void addAttendanceMsg() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, attendanceData.getGroupId()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_NAME, attendanceData.getGroupName()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_NAME, attendanceData.getName()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ADDRESS, attendanceData.getAddress()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LONGITUDE, attendanceData.getLongitude()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LATITUDE, attendanceData.getLatitude()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MEMBERS, attendanceData.getMembers()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVIATION, attendanceData.getDeviation()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WORK_DATE, attendanceData.getWorkDate()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WIFI, attendanceData.getWifiMsg()));

        CreateAttendanceMsg createAttendanceMsg = new CreateAttendanceMsg(mHandler.obtainMessage(ADD_NEW_ATTENDANCE), this);
        if (mAttendanceType == 0){
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_START_WORK_TIME, attendanceData.getStartWorkTime()));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_END_WORK_TIME, attendanceData.getEndWorkTime()));
            if (mIsQuartic == 1) {
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_NOON_END_TIME, attendanceData.getNoonEndTime()));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_NOON_START_TIME, attendanceData.getNoonStartTime()));
            }
            createAttendanceMsg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_NEW;
        } else if (mAttendanceType == 1){
            JSONArray array = new JSONArray();
            if (mSubClass.size() > 0){
                try {
                    for (int i = 0; i < mSubClass.size(); i++) {
                        AttendanceClassData data = mSubClass.get(i);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("sub_name", data.getSub_name());
                        jsonObject.put("is_quartic",data.getIs_quartic());
                        jsonObject.put("start_work_time", data.getStart_work_time());
                        jsonObject.put("end_work_time", data.getEnd_work_time());
                        if (data.getIs_quartic() == 1){
                            jsonObject.put("noon_end_time", data.getNoon_end_time());
                            jsonObject.put("noon_start_time", data.getNoon_start_time());
                        }
                        array.put(jsonObject);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SUB_FORMS, array.toString()));
            createAttendanceMsg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_NEW_SUB;
        }
        createAttendanceMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(createAttendanceMsg);

    }


    /**
     * 更新考勤点
     */
    private void updateAttendanceMsg() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_FORM_ID, attendanceData.get_id()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, attendanceData.getGroupId()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_NAME, attendanceData.getName()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ADDRESS, attendanceData.getAddress()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LONGITUDE, attendanceData.getLongitude()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LATITUDE, attendanceData.getLatitude()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MEMBERS, attendanceData.getMembers()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVIATION, attendanceData.getDeviation()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WORK_DATE, attendanceData.getWorkDate()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WIFI, attendanceData.getWifiMsg()));

        CreateAttendanceMsg createAttendanceMsg = new CreateAttendanceMsg(mHandler.obtainMessage(UPDATE_ATTENDANCE), this);
        if (mAttendanceType == 0){
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_START_WORK_TIME, attendanceData.getStartWorkTime()));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_END_WORK_TIME, attendanceData.getEndWorkTime()));
            if (mIsQuartic == 1) {
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_NOON_END_TIME, attendanceData.getNoonEndTime()));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_NOON_START_TIME, attendanceData.getNoonStartTime()));
            }
            createAttendanceMsg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_UPDATE;

        } else if (mAttendanceType == 1){
            if (mSubClass.size() > 0){
                JSONArray array = new JSONArray();
                try {
                    for (int i = 0; i < mSubClass.size(); i++) {
                        AttendanceClassData data = mSubClass.get(i);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("sub_name", data.getSub_name());
                        jsonObject.put("is_quartic",data.getIs_quartic());
                        jsonObject.put("start_work_time", data.getStart_work_time());
                        jsonObject.put("end_work_time", data.getEnd_work_time());
                        if (data.getIs_quartic() == 1){
                            jsonObject.put("noon_end_time", data.getNoon_end_time());
                            jsonObject.put("noon_start_time", data.getNoon_start_time());
                        }
                        array.put(jsonObject);
                    }
                    nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SUB_FORMS, array.toString()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            createAttendanceMsg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_UPDATE_SUB;
        }
        createAttendanceMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(createAttendanceMsg);

    }

    /**
     * 考勤成员列表
     */
    private void getAttendanceMemberList() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, attendanceData.getGroupId()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_FORM_ID, attendanceData.get_id()));
        GetAttendanceMemberList getAttendanceMemberList = new GetAttendanceMemberList(mHandler.obtainMessage(GET_ATTENDANCE_MEMBER), this);
        getAttendanceMemberList.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_MEMBER_LIST;
        getAttendanceMemberList.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(getAttendanceMemberList);

    }

    /**
     * 考勤成员有重复走的接口
     */
    private void removeMember(String members) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, attendanceData.getGroupId()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MEMBERS, members));
        RemoveMemberMsg removeMemberMsg = new RemoveMemberMsg(mHandler.obtainMessage(REMOVE_ATTENDANCE_MEMBER));
        removeMemberMsg.mApi = AsynHttpClient.API_REMOVE_ATTENDANCE_MEMBER;
        removeMemberMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(removeMemberMsg);

    }


    private void setWorkDate() {
        if (StringUtil.isEmpty(mWorkDate)){
            return;
        }
        if ("1,2,3,4,5".equals(mWorkDate)) {
            mTvWorkDate.setText("工作日");
        } else {
            if (!StringUtil.isEmpty(mWorkDate)) {
                StringBuilder sb = new StringBuilder();
                String weeks[] = mWorkDate.split(",");
                for (String week : weeks) {
                    if ("1".equals(week)) {
                        sb.append("周一").append(",");
                    } else if ("2".equals(week)) {
                        sb.append("周二").append(",");
                    } else if ("3".equals(week)) {
                        sb.append("周三").append(",");
                    } else if ("4".equals(week)) {
                        sb.append("周四").append(",");
                    } else if ("5".equals(week)) {
                        sb.append("周五").append(",");
                    } else if ("6".equals(week)) {
                        sb.append("周六").append(",");
                    } else if ("7".equals(week)) {
                        sb.append("周日").append(",");
                    }
                }
                mTvWorkDate.setText(sb.substring(0, sb.length() - 1));
            }
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                showCancelSetDlg();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void updateTypeView(int type) {
        if (type == 0) {
            mTvStartTimeText1.setText("上班时间");
            mTvEndTimeText2.setText("下班时间");
            mRlEndTime1.setVisibility(View.GONE);
            mRlStartTime2.setVisibility(View.GONE);
            mTypeLine.setVisibility(View.GONE);
            mTvTypeOne.setBackgroundDrawable(getResources().getDrawable(R.drawable.attendance_type_bg1));
            mTvTypeTwo.setBackgroundDrawable(getResources().getDrawable(R.drawable.attendance_type_bg2));
            mTvTypeOne.setTextColor(getResources().getColor(R.color.orange_sign_normal));
            mTvTypeTwo.setTextColor(getResources().getColor(R.color.schedule_day_bg));
        } else {
            mTvStartTimeText1.setText("上午上班时间");
            mTvEndTimeText2.setText("下午下班时间");
            mRlEndTime1.setVisibility(View.VISIBLE);
            mRlStartTime2.setVisibility(View.VISIBLE);
            mTypeLine.setVisibility(View.VISIBLE);
            mTvTypeTwo.setBackgroundDrawable(getResources().getDrawable(R.drawable.attendance_type_bg1));
            mTvTypeOne.setBackgroundDrawable(getResources().getDrawable(R.drawable.attendance_type_bg2));
            mTvTypeOne.setTextColor(getResources().getColor(R.color.schedule_day_bg));
            mTvTypeTwo.setTextColor(getResources().getColor(R.color.orange_sign_normal));
        }
    }

    /**
     * 与下一条时间比较
     *
     * @param hour
     * @param minute
     * @param hour2
     * @param minute2
     * @return
     */
    private boolean compareNextTime(int hour, int minute, int hour2, int minute2) {
        if (hour < hour2) {
            return true;
        } else if (hour == hour2) {
            if (minute < minute2) {
                return true;
            } else {
                return false;
            }
        } else if (hour > hour2) {
            return false;
        }
        return false;
    }

    /**
     * 与上一条时间比较
     *
     * @param hour
     * @param minute
     * @param hour2
     * @param minute2
     * @return
     */
    private boolean compareLastTime(int hour, int minute, int hour2, int minute2) {
        if (hour > hour2) {
            return true;
        } else if (hour == hour2) {
            if (minute > minute2) {
                return true;
            } else {
                return false;
            }
        } else if (hour < hour2) {
            return false;
        }
        return false;
    }
}
